<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Chat</title>
    <style>
        /* 使页面自适应手机端 */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f7fa;
        }

        /* 样式：使用户ID居中显示 */
        #userId {
            font-size: 18px;
            font-weight: bold;
            text-align: center;
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            width: 90%;
            max-width: 250px;
            margin-left: auto;
            margin-right: auto;
            background-color: #f0f0f0;
            border-radius: 8px;
        }

        /* 样式：右上角的 groupId 输入框和按钮 */
        #groupIdContainer {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 10;
            background-color: #ffffff;
            padding: 10px;
            border-radius: 8px;
            box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
        }

        #groupIdContainer input, #groupIdContainer button {
            padding: 10px;
            margin: 5px;
            border-radius: 4px;
            border: 1px solid #ccc;
        }

        #groupIdContainer input {
            width: 200px;
        }

        #groupIdContainer button {
            cursor: pointer;
            background-color: #007bff;
            color: white;
            border: none;
        }

        #groupIdContainer button:hover {
            background-color: #0056b3;
        }

        /* 样式：当前群聊ID显示 */
        #currentGroupId {
            font-size: 16px;
            font-weight: bold;
            text-align: center;
            margin-top: 20px;
            padding: 12px;
            border: 1px solid #ccc;
            width: 90%;
            max-width: 250px;
            margin-left: auto;
            margin-right: auto;
            background-color: #d3f8e2;
            border-radius: 8px;
            display: none;
        }

        /* 样式：消息区域 */
        #responseText {
            height: 250px;
            width: 100%;
            margin-top: 20px;
            padding: 12px;
            border: 1px solid #ccc;
            border-radius: 8px;
            background-color: #ffffff;
            overflow-y: auto; /* 使文本区域可滚动 */
            max-width: 100%;
            box-sizing: border-box;
        }

        /* 样式：输入框和发送按钮 */
        #sendContainer {
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
            padding: 0 10px;
        }

        #context {
            width: 85%;  /* 确保输入框占大部分空间 */
            padding: 10px;
            border-radius: 8px;
            border: 1px solid #ccc;
            font-size: 16px;
        }

        #sendButton {
            width: 12%;
            padding: 12px;
            cursor: pointer;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
        }

        #sendButton:hover {
            background-color: #0056b3;
        }

        /* 响应式设计：确保在小屏幕上显示正常 */
        @media (max-width: 600px) {
            #userId, #currentGroupId, #groupIdContainer input, #groupIdContainer button {
                width: 90%;
                font-size: 14px;
            }

            #sendContainer {
                flex-direction: column;
            }

            #context {
                width: 95%;
                margin-bottom: 10px;
            }

            #sendButton {
                width: 100%;
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body>

<!-- 显示生成的用户ID -->
<div id="userId"></div>

<!-- 显示当前群聊ID -->
<div id="currentGroupId">当前群聊ID: </div>

<!-- 消息显示区域 -->
<textarea id="responseText" readonly></textarea>

<!-- 发送消息输入框和发送按钮 -->
<div id="sendContainer">
    <input type="text" id="context" placeholder="输入消息">
    <button id="sendButton" onclick="sendMessage()">发送</button>
</div>

<!-- 右上角的 groupId 输入框和加入群聊按钮 -->
<div id="groupIdContainer">
    <input type="text" id="groupIdInput" placeholder="Enter Group ID">
    <button onclick="joinGroup()">加入群聊</button>
</div>

<script>
    // 枚举: 定义status值
    const Status = {
        CONNECT: "1",      // 连接开启
        JOIN_GROUP: "101", // 加入群聊
        SEND_MESSAGE: "102", // 发送消息
        HEARTBEAT: "001"   // 心跳
    };

    var interval;
    var socket;
    var userId = generateUserId();  // 自动生成用户ID
    var isInGroup = false;          // 标识用户是否已加入群聊
    var currentGroupId = "";        // 当前群聊ID

    // 生成一个随机的用户ID（模拟ID生成方式）
    function generateUserId() {
        return 'user_' + Math.floor(Math.random() * 1000000000);  // 随机生成一个ID
    }

    // 显示用户ID在页面中央
    document.getElementById('userId').textContent = '用户ID: ' + userId;

    // 初始化 WebSocket 连接
    function initializeWebSocket() {
        if (window.WebSocket) {
            // socket = new WebSocket("ws://124.223.89.220:58080/webSocket");
            socket = new WebSocket("ws://localhost:58080/webSocket");
            socket.onopen = function() {
                onWebSocketOpen();
            };

            socket.onmessage = function(ev) {
                onWebSocketMessage(ev);
            };

            socket.onclose = function() {
                onWebSocketClose();
            };
        } else {
            alert("当前浏览器不支持webSocket");
        }
    }

    // 连接打开时的处理
    function onWebSocketOpen() {
        console.log("WebSocket 连接已开启");
        sendInitialMessage();
        interval = setInterval(sendHeartbeat, 6000);
    }

    // 连接关闭时的处理
    function onWebSocketClose() {
        console.log("WebSocket 连接已关闭");
        clearInterval(interval);
    }

    // 接收到消息时的处理
    function onWebSocketMessage(ev) {
        console.log("收到消息: " + ev.data);
        try {
            var message = JSON.parse(ev.data);
            var rt = document.getElementById("responseText");
            if (message.code === 0 && message.msg === "success") {
                rt.value += "\n" + "连接成功";
            } else {
                rt.value += "\n" + (message.userId || "未知用户") + " : " + (message.magContent || "无消息内容");
            }
            scrollToBottom();
        } catch (e) {
            var rt = document.getElementById("responseText");
            rt.value += "\n" + ev.data;
            scrollToBottom();
        }
    }

    function sendInitialMessage() {
        socket.send(JSON.stringify({
            status: Status.CONNECT,
            content: { id: userId }
        }));
    }

    function sendHeartbeat() {
        socket.send(JSON.stringify({ status: Status.HEARTBEAT }));
    }

    function sendMessage() {
        if (!isInGroup) {
            alert("请先加入群聊！");
            return;
        }
        var messageContent = document.getElementById("context").value;
        socket.send(JSON.stringify({
            status: Status.SEND_MESSAGE,
            groupId: currentGroupId,
            content: {
                userId: userId,
                magContent: messageContent
            }
        }));
        document.getElementById("context").value = '';
        scrollToBottom();
    }

    function scrollToBottom() {
        var rt = document.getElementById("responseText");
        rt.scrollTop = rt.scrollHeight;
    }

    function joinGroup() {
        var groupId = document.getElementById("groupIdInput").value.trim();
        if (groupId === "") {
            alert("请输入有效的群聊ID");
            return;
        }

        socket.send(JSON.stringify({
            status: Status.JOIN_GROUP,
            groupId: groupId,
            content: { id: userId }
        }));

        currentGroupId = groupId;
        document.getElementById("currentGroupId").style.display = 'block';
        document.getElementById("currentGroupId").textContent = '当前群聊ID: ' + currentGroupId;
        isInGroup = true;  // 标记用户已加入群聊
        document.getElementById("groupIdInput").disabled = true;  // 禁用群聊ID输入框
        document.getElementById("groupIdContainer").querySelector("button").disabled = true;  // 禁用按钮

        document.getElementById("groupIdContainer").style.display = 'none';  // 隐藏群聊输入框
        sendPostRequest()
    }

    // 关闭WebSocket连接
    function closeWebSocket() {
        if (socket) {
            socket.close();
            console.log("WebSocket 连接已关闭");
        }
    }
    function sendPostRequest() {
        const url = 'http://127.0.0.1:8081/wine/group/list';
        const data = {
            groupId: currentGroupId
        };

        // 发送POST请求
        fetch(url, {
            method: 'POST', // 使用POST方法
            headers: {
                'Content-Type': 'application/json' // 设置请求头为JSON格式
            },
            body: JSON.stringify(data) // 请求体内容转换为JSON字符串
        })
            .then(response => response.json()) // 将响应内容解析为JSON
            .then(data => {
                // 打印返回的JSON数据

                const dataPage=data.page;
                dataPage.forEach(function(item, index) {

                    // 如果需要访问元素的索引，可以使用 index
                    const items= JSON.parse(item)
                    console.log(items.message);  // 输出数组中的每个元素
                    if (items.message.includes("已加入群聊")){
                        // var rt = document.getElementById("responseText");
                        // rt.value += "\n" + items.message;
                        // scrollToBottom();
                    }else {
                        const ite= JSON.parse(items.message)
                        var rt = document.getElementById("responseText");
                        rt.value += "\n" +ite.userId+" : "+ ite.magContent;
                        scrollToBottom();
                    }

                });

                // document.getElementById('response').textContent = JSON.stringify(data, null, 2);
            })
            .catch(error => {
                console.error('Error:', error);
                // document.getElementById('response').textContent = '请求失败: ' + error;
            });
    }
    // 监听页面关闭时关闭 WebSocket 连接
    window.addEventListener("beforeunload", function() {
        closeWebSocket();
    });

    // 初始化 WebSocket 连接
    initializeWebSocket();
</script>

</body>
</html>
